# -*- coding:utf-8 -*-
import os
import pymssql
import cx_Oracle
from . import utils

class cn_database:
    def __init__(self, host: object, user: object, pwd: object, db: object, port: object, db_type: object) -> object:
        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = db
        self.port = port
        self.db_type = db_type


    def __GetConnect(self):
        if not  self.db:
            raise(NameError,"没有设置数据库")

        if self.db_type == 'mssql':
            self.conn = pymssql.connect(host=self.host, user=self.user, password=self.pwd, database=self.db, port=self.port, charset="utf8")
        elif self.db_type == 'oracle':
            os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
            dsn = cx_Oracle.makedsn(host=self.host, port=self.port, sid=self.db)
            self.conn = cx_Oracle.connect(user=self.user, password=self.pwd, dsn=dsn)
        else:
            raise(NameError,"数据库类型指定错误")
        cur = self.conn.cursor()
        if not cur:
            raise(NameError,"连接数据库失败")
        else:
            return cur

    @utils.metric
    def exec_query(self,sql):
        cur =  self.__GetConnect()
        cur.execute(sql)
        resList = cur.fetchall()

        self.conn.close()
        return resList

    @utils.metric
    def exec_nonquery(self,sql):
        cur = self.__GetConnect()
        cur.execute(sql)
        self.conn.commit()
        self.conn.close()